use serde::{Deserialize, Serialize};
use tauri::State;
use tauri_plugin_store::{StoreBuilder, Store};
use std::sync::Mutex;
use std::path::PathBuf;

#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Service {
    pub name: String,
    pub status: String,
    pub status_text: String,
}

impl Service {
    pub fn new(name: String) -> Self {
        Service {
            name,
            status: "unknown".to_string(),
            status_text: "未知状态".to_string(),
        }
    }
}

// 全局状态管理
pub struct ServicesState {
    pub services: Mutex<Vec<Service>>,
}

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn get_services(state: State<ServicesState>) -> Vec<Service> {
    state.services.lock().unwrap().clone()
}

#[tauri::command]
fn add_service(service: Service, state: State<ServicesState>) -> Result<(), String> {
    let mut services = state.services.lock().unwrap();
    services.push(service);
    Ok(())
}

// 检查服务状态 (Windows)
#[cfg(target_os = "windows")]
#[tauri::command]
fn check_service_status(service_name: String) -> Result<Service, String> {
    let output = run_command_without_window("sc", &["query", &service_name])
        .map_err(|e| format!("无法查询服务 {}: {}", service_name, e))?;

    let mut service = Service::new(service_name);

    let stdout = String::from_utf8_lossy(&output.stdout);
    if stdout.contains("RUNNING") {
        service.status = "running".to_string();
        service.status_text = "运行中".to_string();
    } else if stdout.contains("STOPPED") {
        service.status = "stopped".to_string();
        service.status_text = "已停止".to_string();
    } else {
        service.status = "unknown".to_string();
        service.status_text = "未找到服务".to_string();
    }

    Ok(service)
}

#[cfg(target_os = "windows")]
fn run_command_without_window(cmd: &str, args: &[&str]) -> std::io::Result<std::process::Output> {
    use std::process::Command;
    use std::os::windows::process::CommandExt;

    const CREATE_NO_WINDOW: u32 = 0x08000000;
    Command::new(cmd)
        .args(args)
        .creation_flags(CREATE_NO_WINDOW)
        .output()
}

// 启动服务 (Windows)
#[cfg(target_os = "windows")]
#[tauri::command]
fn start_service(service_name: String) -> Result<String, String> {
    let output = run_command_without_window("net", &["start", &service_name])
        .map_err(|e| format!("无法启动服务 {}: {}", service_name, e))?;

    if output.status.success() {
        Ok(format!("服务 {} 启动成功", service_name))
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        Err(format!("启动服务 {} 失败: {}", service_name, stderr))
    }
}


#[cfg(target_os = "windows")]
#[tauri::command]
fn stop_service(service_name: String) -> Result<String, String> {
    let output = run_command_without_window("net", &["stop", &service_name])
        .map_err(|e| format!("无法停止服务 {}: {}", service_name, e))?;

    if output.status.success() {
        Ok(format!("服务 {} 停止成功", service_name))
    } else {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if stderr.contains("is not started") || stderr.contains("没有启动") {
            Ok(format!("服务 {} 已经处于停止状态", service_name))
        } else {
            Err(format!("停止服务 {} 失败: {}", service_name, stderr))
        }
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_opener::init())
        .plugin(tauri_plugin_store::Builder::default().build())
        .invoke_handler(tauri::generate_handler![
            greet,
            get_services,
            add_service, check_service_status, start_service, stop_service])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}